import matplotlib
matplotlib.use('Agg')  # 设置后端为Agg，必须在导入pyplot之前设置

import os
import re
import matplotlib.pyplot as plt
import networkx as nx
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.colors as mcolors
import numpy as np
import io
from PIL import Image

def parse_bench(bench_path):
    """读取bench文件，解析为节点和边的信息"""
    print(f"[DEBUG] 开始解析bench文件: {bench_path}")
    
    nodes = {}  # 存储节点信息: {node_name: {"type": gate_type, "level": level}}
    edges = []  # 存储边信息: [(from_node, to_node)]
    
    try:
        # 读取bench文件
        with open(bench_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            
        print(f"[DEBUG] 成功读取bench文件，共 {len(lines)} 行")
    except Exception as e:
        print(f"[ERROR] 读取bench文件失败: {str(e)}")
        return {}, [], [], []
    
    # 解析输入和输出声明
    inputs = []
    outputs = []
    gate_connections = {}
    
    for line_num, line in enumerate(lines, 1):
        try:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            
            # 解析输入
            if line.startswith('INPUT('):
                input_name = re.search(r'INPUT\((.*?)\)', line).group(1)
                inputs.append(input_name)
                nodes[input_name] = {"type": "INPUT", "level": 0}
                
            # 解析输出
            elif line.startswith('OUTPUT('):
                output_name = re.search(r'OUTPUT\((.*?)\)', line).group(1)
                outputs.append(output_name)
                
            # 解析逻辑门
            elif '=' in line:
                parts = line.split('=')
                gate_output = parts[0].strip()
                gate_expr = parts[1].strip()
                
                # 判断门类型
                gate_type = None
                inputs_to_gate = []
                
                if gate_expr.startswith('NOT('):
                    gate_type = "NOT"
                    inputs_to_gate = [re.search(r'NOT\((.*?)\)', gate_expr).group(1)]
                elif gate_expr.startswith('BUFF('):
                    gate_type = "BUFF"
                    inputs_to_gate = [re.search(r'BUFF\((.*?)\)', gate_expr).group(1)]
                elif gate_expr.startswith('AND('):
                    gate_type = "AND"
                    inputs_str = re.search(r'AND\((.*?)\)', gate_expr).group(1)
                    inputs_to_gate = [x.strip() for x in inputs_str.split(',')]
                elif gate_expr.startswith('OR('):
                    gate_type = "OR"
                    inputs_str = re.search(r'OR\((.*?)\)', gate_expr).group(1)
                    inputs_to_gate = [x.strip() for x in inputs_str.split(',')]
                elif gate_expr.startswith('NAND('):
                    gate_type = "NAND"
                    inputs_str = re.search(r'NAND\((.*?)\)', gate_expr).group(1)
                    inputs_to_gate = [x.strip() for x in inputs_str.split(',')]
                elif gate_expr.startswith('NOR('):
                    gate_type = "NOR"
                    inputs_str = re.search(r'NOR\((.*?)\)', gate_expr).group(1)
                    inputs_to_gate = [x.strip() for x in inputs_str.split(',')]
                elif gate_expr.startswith('XOR('):
                    gate_type = "XOR"
                    inputs_str = re.search(r'XOR\((.*?)\)', gate_expr).group(1)
                    inputs_to_gate = [x.strip() for x in inputs_str.split(',')]
                    
                if gate_type:
                    nodes[gate_output] = {"type": gate_type, "level": -1}  # 先设置为-1，后面会计算
                    gate_connections[gate_output] = inputs_to_gate
                    for input_node in inputs_to_gate:
                        edges.append((input_node, gate_output))
        except Exception as e:
            print(f"[WARNING] 解析第 {line_num} 行时出错: {str(e)}")
            continue
    
    print(f"[DEBUG] 解析完成: 输入节点 {len(inputs)}, 输出节点 {len(outputs)}, 门 {len(gate_connections)}, 边 {len(edges)}")
    return nodes, edges, inputs, outputs

def draw_circuit(bench_path, output_file=None, show=True):
    """
    绘制电路图
    
    Args:
        bench_path: bench文件路径
        output_file: 输出图片路径
        show: 是否显示图形
        
    Returns:
        bool: 绘制是否成功
    """
    print(f"[DEBUG] 开始绘制电路图: {bench_path}")
    
    try:
        # 检查输入文件
        if not os.path.exists(bench_path):
            print(f"[ERROR] 找不到bench文件: {bench_path}")
            return False
            
        # 确保输出目录存在
        if output_file:
            output_dir = os.path.dirname(output_file)
            if not os.path.exists(output_dir):
                os.makedirs(output_dir, exist_ok=True)
                print(f"[DEBUG] 创建输出目录: {output_dir}")
        
        # 解析电路
        nodes, edges, inputs, outputs = parse_bench(bench_path)
        if not nodes or not edges:
            print("[ERROR] 解析电路失败")
            return False
            
        # 创建图形
        plt.clf()  # 清除当前图形
        
        # 根据节点数量动态调整图形大小
        node_count = len(nodes)
        width = max(12, min(24, node_count / 20))
        height = max(8, min(16, node_count / 30))
        dpi = min(150, max(100, 1000 // width))  # 动态调整DPI
        
        fig = plt.figure(figsize=(width, height), dpi=dpi)
        
        # 创建有向图
        G = nx.DiGraph()
        
        # 添加节点和属性
        for node, attr in nodes.items():
            G.add_node(node, **attr)
            
        # 添加边
        G.add_edges_from(edges)
        
        # 设置节点颜色和大小
        node_colors = []
        node_sizes = []
        for node in G.nodes():
            if node in inputs:
                node_colors.append('#ADD8E6')  # 浅蓝色
                node_sizes.append(800)
            elif node in outputs:
                node_colors.append('#90EE90')  # 浅绿色
                node_sizes.append(800)
            else:
                node_colors.append('#F0F0F0')  # 浅灰色
                node_sizes.append(500)
        
        # 使用分层布局
        try:
            # 首先尝试使用分层布局
            pos = nx.kamada_kawai_layout(G)
            
            # 调整节点位置以避免重叠
            pos = nx.spring_layout(G, pos=pos, k=1.5, iterations=50)
        except:
            # 如果分层布局失败，回退到弹簧布局
            pos = nx.spring_layout(G, k=2, iterations=100)
        
        # 绘制边（先绘制边，这样它们会在节点下面）
        nx.draw_networkx_edges(G, pos,
                             edge_color='gray',
                             arrows=True,
                             arrowsize=10,
                             alpha=0.5,
                             width=0.5)
        
        # 绘制节点
        nx.draw_networkx_nodes(G, pos,
                             node_color=node_colors,
                             node_size=node_sizes)
        
        # 绘制标签
        label_pos = {k: (v[0], v[1] + 0.02) for k, v in pos.items()}  # 稍微上移标签位置
        nx.draw_networkx_labels(G, label_pos,
                              font_size=max(6, min(8, 1000 / np.sqrt(node_count))),  # 动态调整字体大小
                              font_weight='bold',
                              font_family='sans-serif')
        
        # 添加图例
        legend_elements = [
            plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#ADD8E6',
                      markersize=10, label='Input'),
            plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#90EE90',
                      markersize=10, label='Output'),
            plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#F0F0F0',
                      markersize=10, label='Gate')
        ]
        plt.legend(handles=legend_elements, loc='upper right', fontsize=8)
        
        # 设置标题
        plt.title(f"Circuit: {os.path.basename(bench_path)}", pad=20, fontsize=10)
        
        # 调整布局
        plt.tight_layout()
        
        # 保存图形
        if output_file:
            print(f"[DEBUG] 保存图像至: {output_file}")
            plt.savefig(output_file, bbox_inches='tight', dpi=dpi)
            
            # 验证图像是否保存成功
            if os.path.exists(output_file) and os.path.getsize(output_file) > 0:
                print("[DEBUG] 图像保存成功")
            else:
                print("[ERROR] 图像保存失败")
                return False
        
        # 显示图形
        if show:
            plt.show()
        else:
            plt.close()
        
        return True
        
    except Exception as e:
        print(f"[ERROR] 绘制电路图时出错: {str(e)}")
        import traceback
        print(traceback.format_exc())
        return False

def generate_circuit_image(bench_path, format='png', dpi=300):
    """
    生成电路图像并返回图像数据
    
    Args:
        bench_path: bench文件路径
        format: 图像格式 ('png' 或 'jpg')
        dpi: 图像分辨率
        
    Returns:
        bytes: 图像数据，如果失败则返回None
    """
    print(f"[DEBUG] 开始生成电路图像: {bench_path}, format={format}, dpi={dpi}")
    
    try:
        # 创建临时图像文件
        import tempfile
        with tempfile.NamedTemporaryFile(suffix=f'.{format}', delete=False) as tmp_file:
            temp_path = tmp_file.name
            
        # 绘制电路图
        success = draw_circuit(bench_path, temp_path, show=False)
        if not success:
            print("[ERROR] 绘制电路图失败")
            return None
            
        # 读取图像数据
        try:
            with open(temp_path, 'rb') as f:
                image_data = f.read()
            print(f"[DEBUG] 成功读取图像数据，大小: {len(image_data)} bytes")
            return image_data
        except Exception as e:
            print(f"[ERROR] 读取图像数据失败: {str(e)}")
            return None
        finally:
            # 清理临时文件
            try:
                os.remove(temp_path)
            except Exception as e:
                print(f"[WARNING] 清理临时文件失败: {str(e)}")
                
    except Exception as e:
        print(f"[ERROR] 生成电路图像失败: {str(e)}")
        import traceback
        print(traceback.format_exc())
        return None

def compare_circuits(bench_path1, bench_path2, output_path=None):
    """
    比较两个电路图并生成对比图
    
    Args:
        bench_path1: 第一个bench文件路径
        bench_path2: 第二个bench文件路径
        output_path: 输出图像路径
        
    Returns:
        bool: 比较是否成功
    """
    print(f"[DEBUG] 开始比较电路图: \n  1: {bench_path1}\n  2: {bench_path2}")
    
    try:
        # 检查输入文件
        if not os.path.exists(bench_path1) or not os.path.exists(bench_path2):
            print("[ERROR] 输入文件不存在")
            return False
            
        # 创建图形
        plt.clf()
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 8))
        
        # 绘制第一个电路
        nodes1, edges1, inputs1, outputs1 = parse_bench(bench_path1)
        if not nodes1 or not edges1:
            print("[ERROR] 解析第一个电路失败")
            return False
            
        G1 = nx.DiGraph()
        for node, attr in nodes1.items():
            G1.add_node(node, **attr)
        G1.add_edges_from(edges1)
        
        pos1 = nx.spring_layout(G1)
        nx.draw(G1, pos1, ax=ax1, with_labels=True,
                node_color=['lightblue' if n in inputs1 else 'lightgreen' if n in outputs1 else 'lightgray' for n in G1.nodes()],
                node_size=300, font_size=6, font_weight='bold',
                arrows=True, edge_color='gray', arrowsize=15)
        ax1.set_title(f"Circuit 1: {os.path.basename(bench_path1)}")
        
        # 绘制第二个电路
        nodes2, edges2, inputs2, outputs2 = parse_bench(bench_path2)
        if not nodes2 or not edges2:
            print("[ERROR] 解析第二个电路失败")
            return False
            
        G2 = nx.DiGraph()
        for node, attr in nodes2.items():
            G2.add_node(node, **attr)
        G2.add_edges_from(edges2)
        
        pos2 = nx.spring_layout(G2)
        nx.draw(G2, pos2, ax=ax2, with_labels=True,
                node_color=['lightblue' if n in inputs2 else 'lightgreen' if n in outputs2 else 'lightgray' for n in G2.nodes()],
                node_size=300, font_size=6, font_weight='bold',
                arrows=True, edge_color='gray', arrowsize=15)
        ax2.set_title(f"Circuit 2: {os.path.basename(bench_path2)}")
        
        # 添加比较信息
        plt.figtext(0.5, 0.02,
                   f'Nodes: {len(G1.nodes())} vs {len(G2.nodes())}\n'
                   f'Edges: {len(G1.edges())} vs {len(G2.edges())}\n'
                   f'Inputs: {len(inputs1)} vs {len(inputs2)}\n'
                   f'Outputs: {len(outputs1)} vs {len(outputs2)}',
                   ha='center', va='center', bbox=dict(facecolor='white', alpha=0.8))
        
        # 保存图像
        if output_path:
            print(f"[DEBUG] 保存比较图像至: {output_path}")
            plt.savefig(output_path, bbox_inches='tight', dpi=100)
            
            # 验证图像是否保存成功
            if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
                print("[DEBUG] 比较图像保存成功")
            else:
                print("[ERROR] 比较图像保存失败")
                return False
        
        plt.close()
        return True
        
    except Exception as e:
        print(f"[ERROR] 比较电路图失败: {str(e)}")
        import traceback
        print(traceback.format_exc())
        return False

class CircuitVisualizer:
    """用于在GUI应用程序中可视化电路图的类"""
    
    def __init__(self, bench_dir=None):
        """
        初始化可视化器
        
        参数:
            bench_dir: bench文件所在目录，如果为None则使用当前目录
        """
        self.bench_dir = bench_dir if bench_dir else '.'
        self.vis_dir = os.path.join(self.bench_dir, 'visualization')
        self.comp_dir = os.path.join(self.vis_dir, 'comparison')
        
        # 确保输出目录存在
        if not os.path.exists(self.vis_dir):
            os.makedirs(self.vis_dir)
        if not os.path.exists(self.comp_dir):
            os.makedirs(self.comp_dir)
    
    def set_bench_dir(self, bench_dir):
        """设置bench文件目录"""
        self.bench_dir = bench_dir
        self.vis_dir = os.path.join(self.bench_dir, 'visualization')
        self.comp_dir = os.path.join(self.vis_dir, 'comparison')
        
        # 确保输出目录存在
        if not os.path.exists(self.vis_dir):
            os.makedirs(self.vis_dir)
        if not os.path.exists(self.comp_dir):
            os.makedirs(self.comp_dir)
    
    def visualize_circuit(self, bench_file, output_type='image', output_path=None, show=False):
        """
        可视化单个电路图
        
        参数:
            bench_file: bench文件路径或文件名
            output_type: 输出类型，'image'生成图像，'data'返回二进制数据用于GUI显示
            output_path: 输出图像路径，如果为None则自动生成
            show: 是否显示图像
        
        返回:
            如果output_type为'image'，返回输出图像的路径
            如果output_type为'data'，返回图像的二进制数据
        """
        # 处理bench文件路径
        if not os.path.isabs(bench_file):
            bench_path = os.path.join(self.bench_dir, bench_file)
        else:
            bench_path = bench_file
        
        # 检查文件是否存在
        if not os.path.exists(bench_path):
            raise FileNotFoundError(f"找不到bench文件: {bench_path}")
        
        # 确定输出路径
        if output_path is None and output_type == 'image':
            base_name = os.path.basename(bench_path)
            output_name = os.path.splitext(base_name)[0] + '.png'
            output_path = os.path.join(self.vis_dir, output_name)
        
        if output_type == 'image':
            # 绘制电路图并保存为图像
            draw_circuit(bench_path, output_path, show)
            return output_path
        else:
            # 生成图像数据用于GUI显示
            return generate_circuit_image(bench_path)
    
    def compare_circuits(self, original_bench, modified_bench, title=None, output_type='image', output_path=None, show=False):
        """
        比较两个电路图
        
        参数:
            original_bench: 原始bench文件路径或文件名
            modified_bench: 修改后的bench文件路径或文件名
            title: 比较图的标题
            output_type: 输出类型，'image'生成图像，'data'返回二进制数据用于GUI显示
            output_path: 输出图像路径，如果为None则自动生成
            show: 是否显示图像
        
        返回:
            如果output_type为'image'，返回输出图像的路径
            如果output_type为'data'，返回图像的二进制数据
        """
        # 处理bench文件路径
        if not os.path.isabs(original_bench):
            original_path = os.path.join(self.bench_dir, original_bench)
        else:
            original_path = original_bench
            
        if not os.path.isabs(modified_bench):
            modified_path = os.path.join(self.bench_dir, modified_bench)
        else:
            modified_path = modified_bench
        
        # 检查文件是否存在
        if not os.path.exists(original_path):
            raise FileNotFoundError(f"找不到原始bench文件: {original_path}")
        if not os.path.exists(modified_path):
            raise FileNotFoundError(f"找不到修改后的bench文件: {modified_path}")
        
        # 确定输出路径
        if output_path is None and output_type == 'image':
            original_base = os.path.basename(original_path)
            modified_base = os.path.basename(modified_path)
            output_name = f"compare_{os.path.splitext(original_base)[0]}_{os.path.splitext(modified_base)[0]}.png"
            output_path = os.path.join(self.comp_dir, output_name)
        
        if output_type == 'image':
            # 绘制比较图并保存为图像
            fig = compare_circuits(original_path, modified_path, output_path, show, title)
            plt.close(fig)
            return output_path
        else:
            # 生成比较图的图像数据用于GUI显示
            fig = compare_circuits(original_path, modified_path, None, False, title)
            buf = io.BytesIO()
            fig.savefig(buf, format='png', dpi=100, bbox_inches='tight')
            buf.seek(0)
            plt.close(fig)
            return buf.getvalue()
    
    def batch_visualize(self, circuit_results):
        """
        批量可视化电路图和生成比较
        
        参数:
            circuit_results: 电路测试结果的字典，格式如下:
            {
                'name': 电路名称,
                'baseline_tc': 基准测试覆盖率,
                'cop_tc': COP方法测试覆盖率,
                'dg_tc': DeepTPI方法测试覆盖率,
                'baseline_bench': 基准bench文件路径,
                'cop_bench': COP方法bench文件路径,
                'dg_bench': DeepTPI方法bench文件路径
            }
        
        返回:
            可视化结果的字典，包括所有生成的图像路径
        """
        result = {
            'visualization': {}
        }
        
        name = circuit_results['name']
        baseline_tc = circuit_results['baseline_tc']
        cop_tc = circuit_results['cop_tc']
        dg_tc = circuit_results['dg_tc']
        
        # 可视化基准电路
        baseline_bench = circuit_results['baseline_bench']
        if os.path.exists(baseline_bench):
            baseline_vis_path = os.path.join(self.vis_dir, f"{name}_baseline.png")
            try:
                draw_circuit(baseline_bench, baseline_vis_path)
                result['visualization']['baseline'] = baseline_vis_path
            except Exception as e:
                print(f"可视化基准电路失败: {str(e)}")
        
        # 可视化COP方法电路
        cop_bench = circuit_results['cop_bench']
        if os.path.exists(cop_bench):
            cop_vis_path = os.path.join(self.vis_dir, f"{name}_cop.png")
            try:
                draw_circuit(cop_bench, cop_vis_path)
                result['visualization']['cop'] = cop_vis_path
            except Exception as e:
                print(f"可视化COP方法电路失败: {str(e)}")
        
        # 可视化DeepTPI方法电路
        dg_bench = circuit_results['dg_bench']
        if os.path.exists(dg_bench):
            dg_vis_path = os.path.join(self.vis_dir, f"{name}_dg.png")
            try:
                draw_circuit(dg_bench, dg_vis_path)
                result['visualization']['dg'] = dg_vis_path
            except Exception as e:
                print(f"可视化DeepTPI方法电路失败: {str(e)}")
        
        # 创建比较图 - 基准vs COP
        if os.path.exists(baseline_bench) and os.path.exists(cop_bench):
            baseline_cop_comp_path = os.path.join(self.comp_dir, f"{name}_baseline_vs_cop.png")
            try:
                compare_circuits(baseline_bench, cop_bench, 
                               baseline_cop_comp_path, 
                               title=f"Circuit {name}: Baseline vs COP (TC: {baseline_tc:.2f}% vs {cop_tc:.2f}%)")
                result['visualization']['baseline_vs_cop'] = baseline_cop_comp_path
            except Exception as e:
                print(f"比较基准和COP方法电路失败: {str(e)}")
        
        # 创建比较图 - 基准vs DeepTPI
        if os.path.exists(baseline_bench) and os.path.exists(dg_bench):
            baseline_dg_comp_path = os.path.join(self.comp_dir, f"{name}_baseline_vs_dg.png")
            try:
                compare_circuits(baseline_bench, dg_bench, 
                               baseline_dg_comp_path, 
                               title=f"Circuit {name}: Baseline vs DeepTPI (TC: {baseline_tc:.2f}% vs {dg_tc:.2f}%)")
                result['visualization']['baseline_vs_dg'] = baseline_dg_comp_path
            except Exception as e:
                print(f"比较基准和DeepTPI方法电路失败: {str(e)}")
        
        return result
    
    def generate_html_report(self, results, output_path=None):
        """
        生成HTML报告，展示测试结果和可视化图像
        
        参数:
            results: 测试结果数据
            output_path: HTML报告输出路径，如果为None则自动生成
        
        返回:
            HTML报告的路径
        """
        if output_path is None:
            output_path = os.path.join(self.vis_dir, "visualization_report.html")
        
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <title>DeepTPI Test Results Visualization</title>
            <style>
                body {{ font-family: Arial, sans-serif; margin: 20px; }}
                h1, h2, h3 {{ color: #333366; }}
                .summary {{ background-color: #f0f0f0; padding: 15px; border-radius: 5px; margin-bottom: 20px; }}
                .circuit {{ border: 1px solid #ddd; padding: 15px; margin-bottom: 20px; border-radius: 5px; }}
                .circuit h3 {{ margin-top: 0; }}
                .metrics {{ display: flex; justify-content: space-around; margin-bottom: 15px; }}
                .metric {{ text-align: center; }}
                .metric .value {{ font-size: 24px; font-weight: bold; color: #333366; }}
                .metric .label {{ font-size: 14px; color: #666; }}
                .images {{ display: flex; flex-wrap: wrap; justify-content: space-around; }}
                .image-container {{ margin: 10px; text-align: center; }}
                .image-container img {{ max-width: 100%; max-height: 400px; border: 1px solid #ddd; }}
                .image-container .caption {{ margin-top: 5px; font-size: 14px; color: #666; }}
                table {{ border-collapse: collapse; width: 100%; margin-top: 20px; }}
                th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
                th {{ background-color: #f2f2f2; }}
                tr:nth-child(even) {{ background-color: #f9f9f9; }}
            </style>
        </head>
        <body>
            <h1>DeepTPI Test Results Visualization</h1>
            
            <div class="summary">
                <h2>Summary</h2>
                <div class="metrics">
                    <div class="metric">
                        <div class="value">{results['baseline_tc_avg']:.2f}%</div>
                        <div class="label">Average Baseline TC</div>
                    </div>
                    <div class="metric">
                        <div class="value">{results['cop_tc_avg']:.2f}%</div>
                        <div class="label">Average COP TC</div>
                    </div>
                    <div class="metric">
                        <div class="value">{results['dg_tc_avg']:.2f}%</div>
                        <div class="label">Average DeepTPI TC</div>
                    </div>
                    <div class="metric">
                        <div class="value">{results['dg_improvement']:.2f}%</div>
                        <div class="label">DeepTPI Improvement</div>
                    </div>
                    <div class="metric">
                        <div class="value">{results['runtime']:.2f}s</div>
                        <div class="label">Total Runtime</div>
                    </div>
                </div>
                
                <h3>All Circuits</h3>
                <table>
                    <tr>
                        <th>Circuit</th>
                        <th>Nodes</th>
                        <th>PI</th>
                        <th>PO</th>
                        <th>Levels</th>
                        <th>Baseline TC</th>
                        <th>COP TC</th>
                        <th>DeepTPI TC</th>
                        <th>Improvement</th>
                    </tr>
        """
        
        # 添加每个电路的行
        for name, circuit in results['circuits'].items():
            improvement = circuit['dg_tc'] - circuit['baseline_tc']
            html_content += f"""
                    <tr>
                        <td>{name}</td>
                        <td>{circuit['num_nodes']}</td>
                        <td>{circuit['num_pi']}</td>
                        <td>{circuit['num_po']}</td>
                        <td>{circuit['levels']}</td>
                        <td>{circuit['baseline_tc']:.2f}%</td>
                        <td>{circuit['cop_tc']:.2f}%</td>
                        <td>{circuit['dg_tc']:.2f}%</td>
                        <td>{improvement:.2f}%</td>
                    </tr>
            """
        
        html_content += """
                </table>
            </div>
        """
        
        # 为每个电路添加详细信息
        for name, circuit in results['circuits'].items():
            html_content += f"""
            <div class="circuit">
                <h3>Circuit: {name}</h3>
                <div class="metrics">
                    <div class="metric">
                        <div class="value">{circuit['baseline_tc']:.2f}%</div>
                        <div class="label">Baseline TC</div>
                    </div>
                    <div class="metric">
                        <div class="value">{circuit['cop_tc']:.2f}%</div>
                        <div class="label">COP TC</div>
                    </div>
                    <div class="metric">
                        <div class="value">{circuit['dg_tc']:.2f}%</div>
                        <div class="label">DeepTPI TC</div>
                    </div>
                    <div class="metric">
                        <div class="value">{circuit['dg_tc'] - circuit['baseline_tc']:.2f}%</div>
                        <div class="label">Improvement</div>
                    </div>
                </div>
            """
            
            # 添加可视化图像
            if 'visualization' in circuit and circuit['visualization']:
                html_content += """
                <h4>Circuit Visualizations</h4>
                <div class="images">
                """
                
                # 添加基线、COP和DeepTPI方法的可视化
                visualization = circuit['visualization']
                if 'baseline' in visualization:
                    rel_path = os.path.relpath(visualization['baseline'], os.path.dirname(output_path))
                    html_content += f"""
                    <div class="image-container">
                        <img src="{rel_path}" alt="Baseline Circuit">
                        <div class="caption">Baseline Circuit (TC: {circuit['baseline_tc']:.2f}%)</div>
                    </div>
                    """
                
                if 'cop' in visualization:
                    rel_path = os.path.relpath(visualization['cop'], os.path.dirname(output_path))
                    html_content += f"""
                    <div class="image-container">
                        <img src="{rel_path}" alt="COP Circuit">
                        <div class="caption">COP Circuit (TC: {circuit['cop_tc']:.2f}%)</div>
                    </div>
                    """
                
                if 'dg' in visualization:
                    rel_path = os.path.relpath(visualization['dg'], os.path.dirname(output_path))
                    html_content += f"""
                    <div class="image-container">
                        <img src="{rel_path}" alt="DeepTPI Circuit">
                        <div class="caption">DeepTPI Circuit (TC: {circuit['dg_tc']:.2f}%)</div>
                    </div>
                    """
                
                html_content += """
                </div>
                
                <h4>Circuit Comparisons</h4>
                <div class="images">
                """
                
                # 添加比较可视化
                if 'baseline_vs_cop' in visualization:
                    rel_path = os.path.relpath(visualization['baseline_vs_cop'], os.path.dirname(output_path))
                    html_content += f"""
                    <div class="image-container">
                        <img src="{rel_path}" alt="Baseline vs COP">
                        <div class="caption">Baseline vs COP</div>
                    </div>
                    """
                
                if 'baseline_vs_dg' in visualization:
                    rel_path = os.path.relpath(visualization['baseline_vs_dg'], os.path.dirname(output_path))
                    html_content += f"""
                    <div class="image-container">
                        <img src="{rel_path}" alt="Baseline vs DeepTPI">
                        <div class="caption">Baseline vs DeepTPI</div>
                    </div>
                    """
                
                html_content += """
                </div>
                """
            
            html_content += """
            </div>
            """
        
        html_content += """
        </body>
        </html>
        """
        
        # 保存HTML文件
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        return output_path 